package com.weixin.base.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.weixin.base.dao.AdminSiteDao;
import com.weixin.base.dao.SiteDao;
import com.weixin.base.service.AdminSiteService;
import com.weixin.base.service.SiteService;
import com.weixin.base.util.Tools;
import com.weixin.base.util.WeixinUtil;
import com.weixin.entity.TbWxCustomMenu;
import com.weixin.entity.TbWxMenu;
import com.weixin.entity.TbWxText;
import com.weixin.entity.message.AccessToken;
import com.weixin.entity.message.Button;
import com.weixin.entity.message.CommonButton;
import com.weixin.entity.message.ComplexButton;
import com.weixin.entity.message.Menu;
import com.weixin.entity.message.ViewButton;

@Service("adminSiteService")
public class AdminSiteServiceImpl implements AdminSiteService {

	@Autowired
	private AdminSiteDao adminSiteDao;
	
	/**
	 * 首页模版查询
	 */
	public int selectSiteTemplate(int nUserId){
		return adminSiteDao.selectSiteTemplate(nUserId);
	}
	
	/**
	 * 修改微信模版
	 */
	public int updateSiteTemplate(int nUserId,int nTemplateId){
		return adminSiteDao.updateSiteTemplate(nUserId, nTemplateId);
	}

	/**
	 * 自定义菜单同步 result 返回值：1.成功 2.失败
	 */
	public int syncCustomMenu(int userId) {

		int result = 0;

		Map<String, Object> apps = adminSiteDao.selectApp(userId);
		AccessToken at = WeixinUtil.getAccessToken(Tools.convertRs(apps.get("sAppID")), Tools.convertRs(apps.get("sAppSecret")));

		if (null != at) {
			// 调用接口创建菜单
			result = WeixinUtil.createMenu(getMenus(userId), at.getToken());
			if (0 == result) {
				result = 1;
			}
		}
		return result;
	}

	/**
	 * 自定义菜单删除 result 返回值：1.成功 2.失败
	 */
	public int delSyncCustomMenu(int userId) {
		int result = 0;

		Map<String, Object> apps = adminSiteDao.selectApp(userId);
		AccessToken at = WeixinUtil.getAccessToken(Tools.convertRs(apps.get("sAppID")), Tools.convertRs(apps.get("sAppSecret")));

		if (null != at) {
			// 调用接口创建菜单
			result = WeixinUtil.deleteMenu(at.getToken());
			if (0 == result) {
				result = 1;
			}
		}
		return result;
	}

	/**
	 * 组装菜单数据
	 * 
	 * @return
	 */
	public Menu getMenus(int userId) {

		// 查出所有菜单
		List<Map<String, Object>> list = adminSiteDao.searchCustomMenu(userId);
		Map<Integer, TbWxCustomMenu> customMenuMap = new HashMap<Integer, TbWxCustomMenu>();

		/**
		 * 所有菜单放入customMenuMap 用于把子菜单放入父菜单中
		 */
		for (Map<String, Object> map : list) {
			TbWxCustomMenu tbWxCustomMenu = new TbWxCustomMenu();
			tbWxCustomMenu.setLeaf(true);
			tbWxCustomMenu.setNKey(Tools.convertRi(map.get("nKey")));
			tbWxCustomMenu.setNOrder(Tools.convertRi(map.get("nOrder")));
			tbWxCustomMenu.setNPid(Tools.convertRi(map.get("nPid")));
			tbWxCustomMenu.setNtype(Tools.convertRi(map.get("ntype")));
			tbWxCustomMenu.setNUserId(Tools.convertRi(map.get("nUserId")));
			tbWxCustomMenu.setNWxCustomMenuId(Tools.convertRi(map.get("nWxCustomMenuId")));
			tbWxCustomMenu.setSName(Tools.convertRs(map.get("sName")));
			tbWxCustomMenu.setSRemark(Tools.convertRs(map.get("sRemark")));
			tbWxCustomMenu.setNWxUserUrlId(Tools.convertRi(map.get("nWxUserUrlId")));
			tbWxCustomMenu.setSWxUserUrl(Tools.convertRs(map.get("sWxUserUrl")));
			tbWxCustomMenu.setCustomMenuList(new ArrayList<TbWxCustomMenu>());

			customMenuMap.put(tbWxCustomMenu.getNWxCustomMenuId(), tbWxCustomMenu);
		}

		/**
		 * 遍历customMenuMap子菜单放入父菜单中
		 */
		Iterator<Map.Entry<Integer, TbWxCustomMenu>> iterator = customMenuMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<Integer, TbWxCustomMenu> entry = iterator.next();
			TbWxCustomMenu tbWxCustomMenu = entry.getValue();
			if (customMenuMap.containsKey(tbWxCustomMenu.getNPid())) {
				customMenuMap.get(tbWxCustomMenu.getNPid()).getCustomMenuList().add(tbWxCustomMenu);
				customMenuMap.get(tbWxCustomMenu.getNPid()).setLeaf(false);
				iterator.remove();
				customMenuMap.remove(entry.getKey());
			}
		}

		Menu menu = new Menu();

		List<Button> mainBtns = new ArrayList<Button>();
		// 将TbWxCustomMenu转化为json格式
		for (Map.Entry<Integer, TbWxCustomMenu> entry : customMenuMap.entrySet()) {
			TbWxCustomMenu tbWxCustomMenu = entry.getValue();

			// 有子菜单的情况
			if (tbWxCustomMenu.getCustomMenuList().size() > 0) {
				ComplexButton mainBtn = new ComplexButton();
				mainBtn.setName(tbWxCustomMenu.getSName());
				List<Button> subbtn = new ArrayList<Button>();
				for (TbWxCustomMenu entity : tbWxCustomMenu.getCustomMenuList()) {
					if (entity.getNtype() == 1) {
						CommonButton cbtn = new CommonButton();
						cbtn.setName(entity.getSName());
						cbtn.setType("click");
						cbtn.setKey("" + entity.getNKey());
						subbtn.add(cbtn);
					} else if (entity.getNtype() == 2) {
						ViewButton vbtn = new ViewButton();
						vbtn.setName(entity.getSName());
						vbtn.setType("view");
						vbtn.setUrl(entity.getSWxUserUrl());
						subbtn.add(vbtn);
					}
				}
				mainBtn.setSub_button(subbtn);
				mainBtns.add(mainBtn);

				// 没有子菜单的情况
			} else {
				if (tbWxCustomMenu.getNtype() == 1) {
					CommonButton cbtn = new CommonButton();
					cbtn.setName(tbWxCustomMenu.getSName());
					cbtn.setType("click");
					cbtn.setKey("" + tbWxCustomMenu.getNKey());
					mainBtns.add(cbtn);
				} else if (tbWxCustomMenu.getNtype() == 2) {
					ViewButton vbtn = new ViewButton();
					vbtn.setName(tbWxCustomMenu.getSName());
					vbtn.setType("view");
					vbtn.setUrl(tbWxCustomMenu.getSWxUserUrl());
					mainBtns.add(vbtn);
				}
			}
		}

		menu.setButton(mainBtns);
		return menu;
	}

	/**
	 * 删除自定义菜单 result 返回值：1.成功 2.失败
	 */
	public int delCustomMenu(int nWxCustomMenuId) {
		return adminSiteDao.delCustomMenu(nWxCustomMenuId);
	}

	/**
	 * 修改自定义菜单 result 返回值：1.成功 2.失败
	 */
	public int updateCustomMenu(TbWxCustomMenu tbWxCustomMenu) {
		return adminSiteDao.updateCustomMenu(tbWxCustomMenu);
	}

	/**
	 * 添加自定义菜单 result 返回值：1.成功 2.失败
	 */
	public int saveCustomMenu(TbWxCustomMenu tbWxCustomMenu) {
		return adminSiteDao.saveCustomMenu(tbWxCustomMenu);
	}

	public int delSiteMenu(int nWxMenuId) {
		return adminSiteDao.delSiteMenu(nWxMenuId);
	}

	public int saveSiteMenu(TbWxMenu tbWxMenu) {
		return adminSiteDao.saveSiteMenu(tbWxMenu);
	}

	public Page searchSiteMenu(PageRequest<Map> pageRequest, int userid, int ntype) {
		return adminSiteDao.searchSiteMenu(pageRequest, userid, ntype);
	}

	public int updateSiteMenu(TbWxMenu tbWxMenu) {
		return adminSiteDao.updateSiteMenu(tbWxMenu);
	}

	/**
	 * 添加文章记录 result 返回值：1.成功 2.失败
	 */
	public int saveSiteText(TbWxText tbWxText) {
		return adminSiteDao.saveSiteText(tbWxText);
	}

	/**
	 * 查询文章消息
	 * 
	 * @return pageRequest:分页类 userid:用户ID ntype：类型（1有效2无效）
	 */
	public Page searchSiteText(PageRequest<Map> pageRequest, int userid, int ntype) {
		return adminSiteDao.searchSiteText(pageRequest, userid, ntype);
	}

	/**
	 * 修改文章记录 result 返回值：1.成功 2.失败
	 */
	public int updateSiteText(TbWxText tbWxText) {
		return adminSiteDao.updateSiteText(tbWxText);
	}

	/**
	 * 删除文章记录 result 返回值：1.成功 2.失败
	 */
	public int delSiteText(int nwxTextId) {
		return adminSiteDao.delSiteText(nwxTextId);
	}

	/**
	 * 查询自定义菜单
	 */
	public String searchCustomMenu(int nuserId) {

		// 查出所有菜单
		List<Map<String, Object>> list = adminSiteDao.searchCustomMenu(nuserId);
		Map<Integer, TbWxCustomMenu> customMenuMap = new HashMap<Integer, TbWxCustomMenu>();
		StringBuffer jsonMenu = new StringBuffer("[");

		/**
		 * 所有菜单放入customMenuMap 用于把子菜单放入父菜单中
		 */
		for (Map<String, Object> map : list) {
			TbWxCustomMenu tbWxCustomMenu = new TbWxCustomMenu();
			tbWxCustomMenu.setLeaf(true);
			tbWxCustomMenu.setNKey(Tools.convertRi(map.get("nKey")));
			tbWxCustomMenu.setNOrder(Tools.convertRi(map.get("nOrder")));
			tbWxCustomMenu.setNPid(Tools.convertRi(map.get("nPid")));
			tbWxCustomMenu.setNtype(Tools.convertRi(map.get("ntype")));
			tbWxCustomMenu.setNUserId(Tools.convertRi(map.get("nUserId")));
			tbWxCustomMenu.setNWxCustomMenuId(Tools.convertRi(map.get("nWxCustomMenuId")));
			tbWxCustomMenu.setSName(Tools.convertRs(map.get("sName")));
			tbWxCustomMenu.setSRemark(Tools.convertRs(map.get("sRemark")));
			tbWxCustomMenu.setNWxUserUrlId(Tools.convertRi(map.get("nWxUserUrlId")));
			tbWxCustomMenu.setSWxUserUrl(Tools.convertRs(map.get("sWxUserUrl")));
			tbWxCustomMenu.setCustomMenuList(new ArrayList<TbWxCustomMenu>());

			customMenuMap.put(tbWxCustomMenu.getNWxCustomMenuId(), tbWxCustomMenu);
		}

		/**
		 * 遍历customMenuMap子菜单放入父菜单中
		 */
		Iterator<Map.Entry<Integer, TbWxCustomMenu>> iterator = customMenuMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<Integer, TbWxCustomMenu> entry = iterator.next();
			TbWxCustomMenu tbWxCustomMenu = entry.getValue();
			if (customMenuMap.containsKey(tbWxCustomMenu.getNPid())) {
				customMenuMap.get(tbWxCustomMenu.getNPid()).getCustomMenuList().add(tbWxCustomMenu);
				customMenuMap.get(tbWxCustomMenu.getNPid()).setLeaf(false);
				iterator.remove();
				customMenuMap.remove(entry.getKey());
			}
		}

		// 将TbWxCustomMenu转化为json格式
		for (Map.Entry<Integer, TbWxCustomMenu> entry : customMenuMap.entrySet()) {
			jsonMenu.append(JSONObject.fromObject(entry.getValue()).toString());
		}

		jsonMenu.append("]");
		String result = jsonMenu.toString();

		// json格式容错处理
		result = result.replaceAll("customMenuList", "children").replaceAll("SName", "text").replaceAll("\"children\":\\[\\],", "");
		result = result.replaceAll("NWxCustomMenuId", "id").replaceAll("\\}\\{", "\\},\\{");
		return result;
	}

}
